﻿import mermaid from '../../../../_content/CommonRcl/lib/mermaid/mermaid.esm.min.mjs';

//import "../Chart.js/chart.umd.min.js";
mermaid.initialize({ startOnLoad: true, securityLevel: 'loose' });


export function clickAnchor(ancId) {
    //console.log('ancId',ancId);
    globalCsThis.invokeMethodAsync('ClickAnchor',ancId);
}
export function clickBranch(brnId) {
    //console.log('brnId',brnId);
    globalCsThis.invokeMethodAsync('ClickBranch', brnId);
}

let globalCsThis = null;

export async function renderMermaidDiv(mermaidDivId, mermaidScript, csThis, ancDivIds,brnDivIds) {
    //console.log('mermaidScript', mermaidScript);
    globalCsThis = csThis;
    //console.log('mermaid', mermaid);

    let mermaidDiv = document.getElementById(mermaidDivId);
    //console.log('mermaidDiv', mermaidDiv);
    //const { svg } = await mermaid.render(mermaidDivId, mermaidScript);
    //const { svg } = await mermaid.render(mermaidDivId,
    //    'graph TB\na-->b');
    mermaidDiv.innerHTML = mermaidScript;
    //console.log('mermaidDiv', mermaidDiv);
    //console.log('mermaidScript', mermaidScript);
    //let dp=mermaidDiv.getAttribute('data-processed');
    //console.log('dp', dp);
    //mermaidDiv.setAttribute('data-processed', false);
    mermaidDiv.removeAttribute('data-processed');

    mermaid.run({
        querySelector: '.mermaid',
        postRenderCallback: (id) => {
            //document.getElementById(id)
            //console.log('id', id);
            //console.log('elem', document.getElementById(id));
            for (let ancDivId of ancDivIds) {
                let ancDiv = document.getElementById(ancDivId);
                let ancId = ancDivId.replace('anc-', '');
                let mermaidNodeDiv=(function findMermaidNode(elem) {
                    if (elem.classList.contains('node'))
                        return elem;
                    return findMermaidNode(elem.parentElement);
                })(ancDiv);
                mermaidNodeDiv.addEventListener('click', (e)=>clickAnchor(ancId));
                //console.log('ancDivId', ancDivId);
                //console.log('ancDiv', ancDiv);
            }
            for (let brnDivId of brnDivIds) {
                let brnDiv = document.getElementById(brnDivId);
                let brnId = brnDivId.replace('brn-', '');
                let mermaidNodeDiv = (function findMermaidNode(elem) {
                    if (elem.classList.contains('edgeLabel'))
                        return elem;
                    return findMermaidNode(elem.parentElement);
                })(brnDiv);
                mermaidNodeDiv.addEventListener('click', (e) => clickBranch(brnId));
                //console.log('brnDivId', brnDivId);
                //console.log('brnDiv', brnDiv);
            }
            
        }
    });
}
